﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Collections;
using System.Web;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.Web.Configuration;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using MyGeneration.dOOdads;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Net.Mail;
using System.Net.Mime;
using System.Configuration;
using System.Net;
 
namespace POSSystem.BLL
{
    public class Utilities
    {
        //public static String GenerateBarCode(String strBarCode)
        //{
        //    iTextSharp.text.pdf.Barcode128 barCode = new iTextSharp.text.pdf.Barcode128();
        //    barCode.Code = strBarCode;
        //    barCode.CodeType = iTextSharp.text.pdf.Barcode128.CODE128;
        //    return barCode.CreateImageBarCodeHTML(1, 20);
        //}

        public static String GenerateBarCode(String strBarCode)
        {
            iTextSharp.text.pdf.Barcode128 barCode = new iTextSharp.text.pdf.Barcode128();
            barCode.Code = strBarCode;
            barCode.CodeType = iTextSharp.text.pdf.Barcode128.CODE128;
            return barCode.CreateImageBarCodeHTML(1, 20, GetConfigAppSetting("BlackBar"), GetConfigAppSetting("WhiteBar"));
        }

        public static void PrintControl(Control printedControl, String script)
        {
            StringWriter stringWrite = new StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
            if (printedControl is WebControl)
            {
                Unit w = new Unit(100, UnitType.Percentage); ((WebControl)printedControl).Width = w;
            }

            Page pg = new Page();
            pg.EnableEventValidation = false;
            if (script != string.Empty)
            {
                pg.ClientScript.RegisterStartupScript(pg.GetType(), "PrintJavaScript", script);
            }

            HtmlForm frm = new HtmlForm();
            pg.Controls.Add(frm);
            frm.Attributes.Add("runat", "server");
            frm.Controls.Add(printedControl);
            pg.DesignerInitialize();
            pg.RenderControl(htmlWrite);
            string strHTML = stringWrite.ToString();

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(strHTML);
            HttpContext.Current.Response.Write("<script>window.print();</script>");
            HttpContext.Current.Response.End();
        }

        public static void LoadDropDownList(DropDownList ddl, ICollection collection, string textField, string valueField)
        {
            try
            {
                if (collection != null)
                {
                    //sort contents in ascending order
                    if (collection is DataView)
                    {
                        DataView dv = (DataView)collection;
                        dv.Sort = textField + " ASC";
                    }

                    ddl.DataSource = collection;
                    ddl.DataTextField = textField;
                    ddl.DataValueField = valueField;
                    ddl.DataBind();
                }
                ddl.Items.Insert(0, new ListItem("--Select--", String.Empty));
            }
            catch (Exception ex)
            {
                throw new Exception("Utilities.LoadDropDownList(): " + ex.Message);
            }
        }

        public static void LoadListbox(ListBox lb, ICollection collection, string textField, string valueField)
        {
            try
            {
                if (collection != null)
                {
                    //sort contents in ascending order
                    if (collection is DataView)
                    {
                        DataView dv = (DataView)collection;
                        dv.Sort = textField + " ASC";
                    }

                    lb.DataSource = collection;
                    lb.DataTextField = textField;
                    lb.DataValueField = valueField;
                    lb.DataBind();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Utilities.LoadDropDownList(): " + ex.Message);
            }
        }

        public static void LoadDropDownListNoSelect(DropDownList ddl, ICollection collection, string textField, string valueField)
        {
            try
            {
                if (collection != null)
                {
                    //sort contents in ascending order
                    if (collection is DataView)
                    {
                        DataView dv = (DataView)collection;
                        dv.Sort = textField + " ASC";
                    }

                    ddl.DataSource = collection;
                    ddl.DataTextField = textField;
                    ddl.DataValueField = valueField;
                    ddl.DataBind();
                }
                //ddl.Items.Insert(0, new ListItem("--Select--", String.Empty));
            }
            catch (Exception ex)
            {
                throw new Exception("Utilities.LoadDropDownList(): " + ex.Message);
            }
        }

        public static void LoadDropDownListNoSelectNoSort(DropDownList ddl, ICollection collection, string textField, string valueField)
        {
            try
            {
                if (collection != null)
                {
                    ddl.DataSource = collection;
                    ddl.DataTextField = textField;
                    ddl.DataValueField = valueField;
                    ddl.DataBind();
                }
                //ddl.Items.Insert(0, new ListItem("--Select--", String.Empty));
            }
            catch (Exception ex)
            {
                throw new Exception("Utilities.LoadDropDownList(): " + ex.Message);
            }
        }

        public static void LoadDropDownList(DropDownList ddl, ICollection collection, string textField, string valueField, string firstItem)
        {
            try
            {
                if (collection != null)
                {
                    //sort contents in ascending order
                    if (collection is DataView)
                    {
                        DataView dv = (DataView)collection;
                        dv.Sort = textField + " ASC";
                    }

                    ddl.DataSource = collection;
                    ddl.DataTextField = textField;
                    ddl.DataValueField = valueField;
                    ddl.DataBind();
                }
                ddl.Items.Insert(0, new ListItem(firstItem, String.Empty));
            }
            catch (Exception ex)
            {
                throw new Exception("Utilities.LoadDropDownList(): " + ex.Message);
            }
        }

        public static string CamelStringSplitter(string stringtosplit)
        {
            string words = string.Empty;
            if (!string.IsNullOrEmpty(stringtosplit))
            {
                foreach (char ch in stringtosplit)
                {
                    if (char.IsLower(ch))
                    {
                        words += ch.ToString();
                    }
                    else
                    {
                        words += " " + ch.ToString();
                    }


                }
                return words;
            }
            else
                return string.Empty;
        }
        
        public static void LoadDropDownListNoSort(DropDownList ddl, ICollection collection, string textField, string valueField, string firstItem)
        {
            try
            {
                if (collection != null)
                {
                    ////sort contents in ascending order
                    //if (collection is DataView)
                    //{
                    //    DataView dv = (DataView)collection;
                    //    dv.Sort = textField + " ASC";
                    //}

                    ddl.DataSource = collection;
                    ddl.DataTextField = textField;
                    ddl.DataValueField = valueField;
                    ddl.DataBind();
                }
                ddl.Items.Insert(0, new ListItem(firstItem, String.Empty));
            }
            catch (Exception ex)
            {
                throw new Exception("Utilities.LoadDropDownList(): " + ex.Message);
            }
        }

        public static String GetFullPath(String relativeURL)
        {
            return HttpContext.Current.Server.MapPath(relativeURL);
        }

        public static bool IsValidIMEI(string value)
        {
            return value.Where(c => Char.IsDigit(c)).Reverse()
              .SelectMany((c, i) => ((c - '0') << (i & 1)).ToString())
              .Sum(c => c - '0') % 10 == 0;
        }

        public static string GetConfigAppSetting(string key)
        {
            try
            {
                string value = string.Empty;
                if (HttpContext.Current == null)

                    value = ConfigurationManager.AppSettings[key];
                else
                    value = WebConfigurationManager.AppSettings[key];
                if (string.IsNullOrEmpty(value))
                    return string.Empty;
                return value;
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("Utilities.cs", "GetSysConfigAppSetting", ex.ToString());
                throw ex;
            }
        }

        public static void ExportToExcel(SqlClientEntity table, String excelFile, String[] columns, String[] headers, String title)
        {
            HSSFWorkbook hssfworkbook = new HSSFWorkbook();

            // Set DocumentSummaryInformation
            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = "Home";
            hssfworkbook.DocumentSummaryInformation = dsi;

            // Set SummaryInformation
            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            si.Subject = title;
            hssfworkbook.SummaryInformation = si;

            // Create a sheet for the workbook
            HSSFSheet sheet = null;
            HSSFRow headerRow = null;
            HSSFRow row = null;

            // maximum row number of a sheet is 2^16 = 65536
            const int MAX_ROW_NUMBER = 65000;
            int sheetColumnNumber = columns.Length;

            int sheetNumber = (table.RowCount % MAX_ROW_NUMBER) == 0 ? table.RowCount / MAX_ROW_NUMBER
                : table.RowCount / MAX_ROW_NUMBER + 1;
            int lastSheetRowNumber = (table.RowCount % MAX_ROW_NUMBER) == 0 ? MAX_ROW_NUMBER
                : table.RowCount % MAX_ROW_NUMBER;
            int sheetRowNumber;

            string[] arrColumnHeader = null;

            arrColumnHeader = headers;

            object[] cellVals;

            //insert sheets
            for (int index = 0; index < sheetNumber; index++)
            {
                if (index < (sheetNumber - 1))
                {
                    sheetRowNumber = MAX_ROW_NUMBER;
                }
                else
                {
                    sheetRowNumber = lastSheetRowNumber;
                }

                sheet = hssfworkbook.CreateSheet(excelFile.Replace(".xls", "") + (index + 1).ToString());

                //insert header
                headerRow = sheet.CreateRow(0);

                for (int i = 0; i < sheetColumnNumber; i++)
                {
                    headerRow.CreateCell(i).SetCellValue(arrColumnHeader[i]);
                }

                //insert rows
                for (int i = 1; i <= sheetRowNumber; i++)
                {
                    row = sheet.CreateRow(i);

                    cellVals = new object[columns.Length];
                    for (int j = 0; j < columns.Length; j++)
                        cellVals[j] = table.IsColumnNull(columns[j]) ? "" : table.GetColumn(columns[j]);

                    for (int j = 0; j < sheetColumnNumber; j++)
                    {

                        if (cellVals[j] is Double || cellVals[j] is Decimal)
                        {
                            row.CreateCell(j).SetCellValue(Convert.ToDouble(cellVals[j]));
                        }
                        else if (cellVals[j] is Int32)
                        {
                            row.CreateCell(j).SetCellValue(Convert.ToInt32(cellVals[j]));
                        }
                        else
                        {
                            row.CreateCell(j).SetCellValue(cellVals[j].ToString());
                        }
                    }

                    table.MoveNext();
                }

                // Auto resize grid column
                for (int i = 0; i <= sheetColumnNumber; i++)
                {
                    sheet.AutoSizeColumn(i);
                }

                // Freeze grid header
                sheet.CreateFreezePane(0, 1, 0, 1);
            }

            // Get data stream
            MemoryStream stream = new MemoryStream();
            hssfworkbook.Write(stream);

            // Response configuration
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", excelFile));
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.BinaryWrite(stream.GetBuffer());
            HttpContext.Current.Response.Expires = -1;
            HttpContext.Current.Response.End();
        }

        public static string CreateMD5Hash(string input)
        {
            // Use input string to calculate MD5 hash
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hashBytes = md5.ComputeHash(inputBytes);

            // Convert the byte array to hexadecimal string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("x2"));
                // To force the hex string to lower-case letters instead of
                // upper-case, use he following line instead:
                // sb.Append(hashBytes[i].ToString("x2")); 
            }
            return sb.ToString();
        }

        public static void SendEmail(string mailTo, string mailSubject, string mailBody)
        {
            MailMessage message = new MailMessage();
            SmtpClient smtp = new SmtpClient();

            message.From = new MailAddress(Utilities.GetConfigAppSetting("Email"), "All For You Online");
            string[] recipients = mailTo.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < recipients.Length; i++)
            {
                message.To.Add(new MailAddress(recipients[i]));
            }
            

            message.IsBodyHtml = true;
            message.Subject = mailSubject;
            message.Body = mailBody;

            smtp.Host = Utilities.GetConfigAppSetting("EmailServer");
            //smtp.EnableSsl = true;
            smtp.Port = int.Parse(Utilities.GetConfigAppSetting("EmailPort"));
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new NetworkCredential(Utilities.GetConfigAppSetting("Email"), Utilities.GetConfigAppSetting("EmailPassword"));
            smtp.Send(message);
        }

        public static string GetProductImageUrl(Object url)
        {
            if(url != null && url != DBNull.Value)
                return GetConfigAppSetting("ProductImagePath") + "/" + url.ToString();
            return "";
        }
    }
}
